package com.car.common;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.stonehenge.backend.tools.StaticToolit;
import com.stonehenge.recommender.dao.ASimpleDao;
import org.apache.commons.math3.util.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * @author chengjun E-mail: 18362586403@139.com
 * @version 1.0 Date：2015年11月16日 下午10:18:36 Comment：
 * 目前有子类的：
 * comment gallery user
 */
public abstract class CtrlerHeader extends CtrlerFinals{


    private static final Logger logger = LoggerFactory.getLogger(CtrlerHeader.class);
    
    protected Random rn = new Random();

    /**
     * 每个controller自带的一个解析Json的函数，需在子类重新实现
     * @param postJson
     * @param para
     * @return
     */
    protected abstract String verifyJson(String postJson, String... para);
    
    /**
     * 每个controller自带的一个解析Json的函数,并返回解析的，需在子类重新实现
     * @param postJson
     * @param clazz
     * @param para
     * @return
     */
    protected abstract  <T> Pair<String,T> verifyJson(String postJson, Class<T> clazz,String... para);
    /**
     * 最终的返回，正常的返回
     * @param result
     * @param data
     * @param diff
     * @param code
     * @return
     */
    protected final Map<String, Object> finalReturns(Map<String, Object> result, Map<String, Object> data, long diff, int code) {
        result.put(RETURNTYPE_CODE, code);
        result.put(RETURNTYPE_DATA, data);
        result.put(RETURNTYPE_COST, diff);
        return result;
    }
    
    /**
     * 异常情况的返回
     * @param result
     * @param code
     * @param info
     * @return
     */
    public final static Map<String, Object> exceptionReturn(Map<String, Object> result, int code, String... info /*info,msg*/) {
        result.put(RETURNTYPE_CODE, code);
        result.put(RETURNTYPE_DATA, null);
        if (info != null && info.length > 0)
            result.put(RETURNTYPE_ERRINFO, info[0]);
        if (info != null && info.length > 1)
            result.put(RETURNTYPE_MSG, info[1]);
        return result;

    }
    
    /**
     * 中途返回
     * @param result
     * @param code
     * @param info
     * @return
     */
    public final static Map<String, Object> halfwayReturn(Map<String, Object> result, int code, String... info /*info,msg*/) {
        result.put(RETURNTYPE_CODE, code);
        result.put(RETURNTYPE_DATA, new ArrayList<String>());
        if (info != null && info.length > 0)
            result.put(RETURNTYPE_INFO, info[0]);
        if (info != null && info.length > 1)
            result.put(RETURNTYPE_MSG, info[1]);
        return result;

    }

    //=============================================================
    //=============================================================
    //=======================处理Dao======================================
    //=============================================================
    /**
     * 从指定dao获取指定domain的list
     * @param d
     * @param page
     * @param limit
     * @param para
     * @return
     */
    @SuppressWarnings("unchecked")
    protected <Dao, Domain> List<Domain> getItemsByDao(Dao d, int page, int limit, String... para) {
        try {
            ASimpleDao<Domain> dao = (ASimpleDao<Domain>) d;
            List<Domain> list = dao.getByBatch(page, limit, para);
            return list;
        } catch (Exception e) {
            logger.error("getItemsByDao error:", e);
            return null;
        }

    }
    
    /**
     * 从指定dao获取指定domain的一个样本
     * @param d
     * @param key
     * @param para
     * @return
     */
    @SuppressWarnings("unchecked")
    protected <Dao, Domain> Domain getOneItemByDao(Dao d, String key, String... para) {
        try {
            ASimpleDao<Domain> dao = (ASimpleDao<Domain>) d;
            Domain one = dao.getByKey(key, para);
            return one;
        } catch (Exception e) {
            logger.error("getOneItemByDao error:", e);
            return null;
        }
    }

    /**
     * 向指定dao插入一个序列化的domain
     * @param d
     * @param clazz
     * @param postJson
     * @param para
     * @return
     */
    @SuppressWarnings("unchecked")
    protected <Dao, Domain> int insertItem(Dao d, Class<Domain> clazz, String postJson, String... para) {
        Domain one = null;
        try {
            one = JSON.parseObject(postJson, clazz);
        } catch (JSONException e) {
            logger.error("!!insertItem json parse error",e);
            return -1;
        }
        ASimpleDao<Domain> dao = (ASimpleDao<Domain>) d;;// dao.insertOneRecord(one);
        int flag = dao.insert(one, para);

        return flag;
    }
    /**
     * 向指定dao插入一个实例化的domain
     * @param d
     * @param clazz
     * @param one
     * @param para
     * @return
     */
    @SuppressWarnings("unchecked")
    protected <Dao, Domain> int insertItem(Dao d, Class<Domain> clazz, Domain one, String... para) {
        try {
            ASimpleDao<Domain> dao = (ASimpleDao<Domain>) d;;// dao.insertOneRecord(one);
            int flag = dao.insert(one, para);
            return flag;
        } catch (Exception e) {
            logger.error("insertItem error:", e);
            return 0;
        }
    }
    
    //=============================================================
    //=============================================================
    //=======================处理json======================================
    //=============================================================
    protected static <T> List<T> parseJsonList(String postJson, Class<T> clazz, String... para) {

        if (postJson == null)
            return null;

        List<T> items = null;
        try {
            items = JSON.parseArray(postJson, clazz);
        } catch (JSONException e) {
            logger.error("parseJsonList error:",e);
            return null;
        }
        if (items == null || items.size() < 0) {
            return null;
        }

        return items;
    }
    
    protected static <T> T expandJsonOne(String postJson,Class<T> clazz) {
        T one_json = StaticToolit.parseJsonOrNull(postJson, clazz);
        return one_json; 
    }
    protected static <T> List<T> expandJsonList(String postJson,Class<T> clazz) {
        List<T> list_json = StaticToolit.parseJsonArrayOrNull(postJson, clazz);
        return list_json; 
    }
    protected static JSONObject expandJsonObject(String postJson) {
        JSONObject jsonObject=StaticToolit.parseJSONObjectOrNull(postJson);
        return jsonObject;
    }

	protected static List<JSONObject> getJsonObjectArrayWithKey(JSONObject obj, String key) {
		if (obj == null)
			return null;
		JSONArray arrays = obj.getJSONArray(key);
		if (arrays == null)
			return null;
		Object[] objs = arrays.toArray();
		List<JSONObject> list = Lists.newArrayList();
		for (Object tmpOjb : objs) {
			JSONObject jsonObject = (JSONObject) tmpOjb;
			if (jsonObject == null)
				return null;
			list.add(jsonObject);
		}
		return list;

	}
    
    protected static <T> Pair<String, T> pair(String str,T t) {
    	return new Pair<String, T>(str,t);
    }
    protected static <T> Pair<String, T> pairnull(String str) {
    	return new Pair<String, T>(str,null);
    }
    
    public static <T> Map<T, Object> newPair(T key1, Object obj1,T key2, Object obj2) {
        Map<T, Object> map=Maps.newHashMap();
        if(key1!=null)
        	map.put(key1, obj1);
        if(key2!=null)
        	map.put(key2, obj2);
        return map;
    }
    public static void main(String[] args) {
    	String str="{\"clubid\":\"10002\",\"userid\":\"10072745653068\",\"cost\":1444,\"summary\":\"你的时候就觉得特别幸福？我是你\",\"title\":\"你是我的人是我自己\",\"coverresid\":\"f-3kjcsovv0_exp_image_its97tao_688.jpg\",\"photolist\":[{\"userid\":\"10072745653068\",\"resid\":\"f-3kjcsovv0_exp_image_its97vch_258.jpg\"}],\"type\":1,\"carid\":\"2\"}";
    	
       JSONObject object= expandJsonObject(str) ;
       System.out.println(object);
       
       List<JSONObject> list=getJsonObjectArrayWithKey(object, "photolist");
       System.out.println(list);
		
	}
}

